//
//  OMLoginView.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/4/26.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMLoginView.h"
#import "OMMobileTextField.h"
#import "NSTimer+STBlock.h"
@interface OMLoginView () <OMMobileTextFieldDelegate>
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) OMMobileTextField *phoneTF;
@property (nonatomic, strong) OMTextField *passwordTF;
@property (nonatomic, strong) UIButton *verifyCodeButton;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *loginButton;

@property (nonatomic, assign) BOOL          isGettingVerify;        //是否在获取手机验证码
@property (nonatomic, assign) NSUInteger    count;                  //计时辅助数字60秒
@property (nonatomic, strong) NSTimer       *timer;                 //计时器

@property (nonatomic, strong) UIButton      *environmentButton;     //环境配置按钮(开发模式下可显示)

@end

@implementation OMLoginView
OMLoginView *_instance;
+ (instancetype)sharedInstance
{
    if (!_instance) {
        _instance = [OMLoginView new];
    }
    return _instance;
}

- (instancetype)init
{
    self = [super init];
    [self configure];
    return self;
}

#define kMarginVertical SM_SIZE(30)
#define kMarginHorizon kMarginVertical
#define kTextFieldHeight SM_SIZE(90)
- (void)configure
{

    _backgroundView = [UIView new];
    _backgroundView.backgroundColor = [SM_blackColor colorWithAlphaComponent:.6f];
    [self addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
    @weakify(self);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        @strongify(self);
        [self dismiss];
    }];
    [_backgroundView addGestureRecognizer:tap];


    _contentView = [UIView new];
    _contentView.backgroundColor = SM_whiteColor;
    [self addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];

    _cancelButton = [UIButton new];
    [_cancelButton setImage:[UIImage imageNamed:@"login_cls_18x18_"] forState:UIControlStateNormal];
    [_cancelButton setContentEdgeInsets:UIEdgeInsetsMake(SM_SIZE(10), SM_SIZE(10), SM_SIZE(10), SM_SIZE(10))];
    [self.contentView addSubview:_cancelButton];
    [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(-kMarginHorizon));
        make.top.equalTo(@(kMarginVertical));
    }];
    [[_cancelButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self dismiss];
    }];


    _verifyCodeButton = [UIButton new];
    [_verifyCodeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_verifyCodeButton setContentEdgeInsets:UIEdgeInsetsMake(SM_SIZE(15), SM_SIZE(15), SM_SIZE(15), SM_SIZE(15))];
    [_verifyCodeButton.layer setCornerRadius:4];
    _verifyCodeButton.clipsToBounds = true;
    [_verifyCodeButton sizeToFit];
    [_verifyCodeButton.titleLabel setFont:SM_CFont(28)];
    [_verifyCodeButton setTitleColor:SM_whiteColor forState:UIControlStateNormal];
    [_verifyCodeButton setBackgroundImage:[UIImage imageWithColor:HEXCOLOR(@"#6BCD00")] forState:UIControlStateNormal];
    [_verifyCodeButton setBackgroundImage:[UIImage imageWithColor:SM_disableColor] forState:UIControlStateDisabled];
    [[_verifyCodeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self getVerifyCode:x];
    }];

    _phoneTF = [OMMobileTextField new];
    _phoneTF.selectdisable = YES;
    _phoneTF.om_delegate = self;
    _phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTF.leftViewMode = UITextFieldViewModeAlways;
    _phoneTF.rightViewMode = UITextFieldViewModeAlways;
    _phoneTF.phone = KTSystemStorageSingleton.username;
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;

    _phoneTF.rightView = _verifyCodeButton;
    UIImageView *imageV = [[UIImageView alloc]initWithImage:[UIImage pngNamed:@"login_mobile_21x21_"]];
    [imageV sizeToFit];
    _phoneTF.leftView = imageV;
    _phoneTF.placeholder = @"请填写手机号码";
    _phoneTF.font = SM_CFont(31);
    [self.contentView addSubview:_phoneTF];
    [_phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(kMarginHorizon));
        make.height.equalTo(@(kTextFieldHeight));
        make.right.equalTo(@(-kMarginHorizon));
        make.top.equalTo(_cancelButton.mas_bottom).offset(kMarginVertical);
    }];
    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [self.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_phoneTF.mas_left);
        make.right.equalTo(_phoneTF.mas_right);
        make.top.equalTo(_phoneTF.mas_bottom);
        make.height.equalTo(@.5f);
    }];


    _passwordTF = [OMTextField new];
    _passwordTF.om_delegate = self;
    _passwordTF.leftViewMode = UITextFieldViewModeAlways;
    _passwordTF.enablesReturnKeyAutomatically = YES;
    _passwordTF.autocorrectionType = UITextAutocorrectionTypeNo;
    _passwordTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
    imageV = [[UIImageView alloc]initWithImage:[UIImage pngNamed:@"login_pwd_21x21_"]];
    [imageV sizeToFit];
    _passwordTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _passwordTF.returnKeyType = UIReturnKeyGo;
    _passwordTF.clearButtonMode = UITextFieldViewModeAlways;
    _passwordTF.leftView = imageV;
    _passwordTF.placeholder = @"请输入验证码";
    _passwordTF.font = SM_CFont(31);
    [self.contentView addSubview:_passwordTF];
    [_passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(kMarginHorizon));
        make.height.equalTo(@(kTextFieldHeight));
        make.right.equalTo(@(-kMarginHorizon));
        make.top.equalTo(line.mas_bottom).offset(kMarginVertical);
    }];
    line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [self.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_passwordTF.mas_left);
        make.right.equalTo(_passwordTF.mas_right);
        make.top.equalTo(_passwordTF.mas_bottom);
        make.height.equalTo(@.5f);
    }];


    _loginButton = [UIButton new];
    [_loginButton.titleLabel setFont:SM_CFont(34)];
    [_loginButton.layer setCornerRadius:4];
    _loginButton.clipsToBounds = true;
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [_loginButton setTitleColor:SM_blackColor forState:UIControlStateNormal];
    [_loginButton setTitleColor:SM_whiteColor forState:UIControlStateDisabled];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:SM_disableColor] forState:UIControlStateDisabled];
    [self.contentView addSubview:_loginButton];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(kMarginHorizon+SM_SIZE(10)));
        make.right.equalTo(@(-kMarginHorizon-SM_SIZE(10)));
        make.top.equalTo(line.mas_bottom).offset(SM_SIZE(70));
        make.height.equalTo(@(SM_SIZE(95)));
        make.bottom.equalTo(@(SM_SIZE(-100)));
    }];
    [[_loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self loginAction];
    }];


#ifdef DEBUG
    [self.contentView addSubview:self.environmentButton];
#endif
    if (_environmentButton.superview) {
        [self.environmentButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(SM_SIZE(30)));
            make.left.equalTo(@(SM_SIZE(50)));
        }];
    }


    [self observeSetup];

}

- (void)observeSetup
{
    //监听信号，判断按钮的使能
    @weakify(self);
    [[RACSignal combineLatest:@[
                                self.phoneTF.rac_textSignal,
                                self.passwordTF.rac_textSignal,
                                RACObserve(self, isGettingVerify),
                                ]
                       reduce:^id{
                           @strongify(self);
                           return @(self.phoneTF.text.length && self.passwordTF.text.length);
                       }]
     subscribeNext:^(id x) {
         @strongify(self);
         self.loginButton.enabled = [x boolValue];
         self.verifyCodeButton.enabled = [self.phoneTF.text isMobile] && !self.isGettingVerify;
         [self.verifyCodeButton sizeToFit];
     }];

    //监听登录按钮的点击事件（按下后）
    [[self.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self loginAction];
    }];

}


#pragma mark - Getters
- (UIButton *)environmentButton
{
    if (!_environmentButton) {
        _environmentButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 60)];
        [_environmentButton setTitleColor:SM_grayColor forState:UIControlStateNormal];
        _environmentButton.titleLabel.font = SM_CFont(28);
        [self setEnvironmentButtonTitle:[KTHttpUtils currentMode]];
        [_environmentButton addTarget:self action:@selector(environmentButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_environmentButton sizeToFit];

    }
    return _environmentButton;
}

#pragma mark - OMTextFieldDelegate
- (void)textField:(OMTextField *)textField didFinishedInputAPhone:(NSString *)text
{
//    if ([text isMobile]) {
//        [self getVerifyCode:self.verifyCodeButton];
//    }
}

- (BOOL)textFieldShouldReturn:(OMTextField *)textField
{
    if (textField == self.passwordTF && self.loginButton.enabled) {
        [self loginAction];
    }
    return YES;
}
#pragma mark - Actions
- (void)showInShow:(UIView *)view
{
    [view addSubview:self];
    _backgroundView.backgroundColor = [SM_blackColor colorWithAlphaComponent:0.f];
    [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
    [UIView animateWithDuration:.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{

        _backgroundView.backgroundColor = [SM_blackColor colorWithAlphaComponent:.5f];

    } completion:^(BOOL finished) {

    }];
}

- (void)dismiss
{
    _backgroundView.backgroundColor = [SM_blackColor colorWithAlphaComponent:.5f];
    [UIView animateWithDuration:.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        _backgroundView.backgroundColor = [SM_blackColor colorWithAlphaComponent:0];
        [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(SM_SIZE(0)));
            make.right.equalTo(@(SM_SIZE(0)));
            make.top.equalTo(@(SM_SCREEN_HEIGHT));
        }];
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

/**
 登录按钮点击回调方法
 */
- (void)loginAction
{
    [self endEditing:YES];
    self.loginButton.enabled = NO;
    [OMHUD HUDShieldLoading:nil];

    [KTHttpUtils loginWithUserName:self.phoneTF.phone
                          password:self.passwordTF.text
                          onResult:^(BOOL isSuccess, NSString *message) {
                              if (isSuccess) {
                                  [OMHUD HUDSuccess:@"登录成功"];
                                  [self dismiss];
                                  self.passwordTF.text = nil;
                              }else {
                                  [OMHUD HUDError:message];
                              }
                              self.loginButton.enabled = YES;
                          }];

}



/**
 获取验证码按钮点击回调方法

 @param button 按钮
 */
- (void)getVerifyCode:(UIButton *)button
{
    @weakify(self);
    if (self.isGettingVerify) {
        return;
    }
    [self.passwordTF becomeFirstResponder];
    self.isGettingVerify = YES;
    [OMHUD HUDShieldLoading:nil];
    [KTHttpUtils GET_NOCACHE:@"account/sendLoginSms.jhtml"
                  parameters:@{@"username":self.phoneTF.phone}
                    progress:nil
                  completion:^(id responseObject, BOOL isSuccess, NSString *message) {
                      if (isSuccess) {
                          self.count = 60;
                          self.timer =
                          [NSTimer scheduledTimerWithTimeInterval:1.f
                                                          repeats:YES withCallBack:^{
                                                              @strongify(self);
                                                              [self ticktock];
                                                          }];
                          [self.passwordTF becomeFirstResponder];
                      }else {
                          self.isGettingVerify = NO;
                      }
                      [OMHUD HUDInfo:message];
                  }];
}

//计时器回调方法
- (void)ticktock
{
    if (!self.count) {
        [self.timer invalidate];
        self.isGettingVerify = NO;
        [self.verifyCodeButton setTitle:@"发送验证码" forState:UIControlStateDisabled];
        [self.verifyCodeButton sizeToFit];
        return;
    }
    [self.verifyCodeButton setTitle:[NSString stringWithFormat:@"%@s后重发", @(self.count--)] forState:UIControlStateDisabled];
    [self.verifyCodeButton sizeToFit];
}


/**
 测试按钮点击回调方法
 */
- (void)environmentButtonClick
{
    @weakify(self);
    [self endEditing:YES];
    NSMutableArray *menuList = [NSMutableArray arrayWithCapacity:1];
    [menuList addObject:[DownSheetModel downSheetModelWithIcon:nil andIcon_on:nil andTitle:@"开发环境"]];
    [menuList addObject:[DownSheetModel downSheetModelWithIcon:nil andIcon_on:nil andTitle:@"生产环境"]];
    DownSheet *sheet = [[DownSheet alloc]initWithlist:menuList height:0];
    [sheet setOnSelectAction:^(NSInteger selectedIndex) {
        @strongify(self);
        [KTHttpUtils setServerMode:selectedIndex?KTServerProductMode:KTServerDebugMode];
        [OMHUD HUDSuccess:@"设置成功"];
        [self setEnvironmentButtonTitle:[KTHttpUtils currentMode]];

    }];
    [sheet showInView:SMKeyWindow];
}

/**
 设置环境标题方法
 @param title 标题(开发环境/生产环境)
 */
- (void)setEnvironmentButtonTitle:(NSString *)title
{
    NSString *finialString = [[@"现在是\"" stringByAppendingString:title] stringByAppendingString:@"\",点此切换"];
    NSAttributedString *attributedStr = [[NSAttributedString alloc]initWithString:finialString
                                                                       attributes:@{
                                                                                    NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),
                                                                                    NSForegroundColorAttributeName:SM_lightGrayColor
                                                                                    }];
    [_environmentButton setAttributedTitle:attributedStr
                                  forState:UIControlStateNormal];
}
@end
